package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    private static final Logger log = LoggerFactory.getLogger(ReportServiceImpl.class);
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WorkspaceServiceImpl workspaceService;


    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDateArrayList = new ArrayList<>();
        end = end.plusDays(1);
        while (!begin.equals(end)) {
            localDateArrayList.add(begin);
            begin = begin.plusDays(1);
        }

        List<BigDecimal> monetList = new ArrayList<>();
        localDateArrayList.forEach(item -> {
            LocalDateTime beginTime = LocalDateTime.of(item, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(item, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);

            BigDecimal moneyCount = reportMapper.turnoverStatistics(map);
            if (moneyCount != null) {
                monetList.add(moneyCount);
            } else {
                monetList.add(new BigDecimal(0));
            }
        });

        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setTurnoverList(monetList.stream().map(String::valueOf).collect(Collectors.joining(",")));
        turnoverReportVO.setDateList(localDateArrayList.stream().map(String::valueOf).collect(Collectors.joining(",")));

        return turnoverReportVO;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDateArrayList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();

        end = end.plusDays(1);
        while (!begin.equals(end)) {
            localDateArrayList.add(begin);
            begin = begin.plusDays(1);
        }

        localDateArrayList.forEach(item -> {
            LocalDateTime endTime = LocalDateTime.of(item, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("status", StatusConstant.ENABLE);
            map.put("endTime", endTime);

            Integer totalUserCount = reportMapper.userStatistics(map);
            if (totalUserCount != null) {
                totalUserList.add(totalUserCount);
            } else {
                totalUserList.add(0);
            }

            LocalDateTime beginTime = LocalDateTime.of(item, LocalTime.MIN);
            map.put("beginTime", beginTime);
            Integer newUserCount = reportMapper.userStatistics(map);
            if (totalUserCount != null) {
                newUserList.add(newUserCount);
            } else {
                newUserList.add(0);
            }
        });

        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(localDateArrayList.stream().map(String::valueOf).collect(Collectors.joining(",")));
        userReportVO.setTotalUserList(totalUserList.stream().map(String::valueOf).collect(Collectors.joining(",")));
        userReportVO.setNewUserList(newUserList.stream().map(String::valueOf).collect(Collectors.joining(",")));

        return userReportVO;
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        // 日期列表
        List<LocalDate> localDateArrayList = new ArrayList<>();
        end = end.plusDays(1);
        while (!begin.equals(end)) {
            localDateArrayList.add(begin);
            begin = begin.plusDays(1);
        }


        ArrayList<Integer> orderCountList = new ArrayList<>();
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;

        for (LocalDate date : localDateArrayList) {
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);

            // 订单完成率
            Map map = new HashMap<>();
            map.put("endTime", endTime);
            map.put("beginTime", beginTime);
            map.put("status", null);
            Integer currentOrderCount = reportMapper.getOrderCompletionRateCount(map);
            map.put("status", Orders.COMPLETED);
            Integer currentValidOrderCount = reportMapper.getOrderCompletionRateCount(map);

            // 订单数列表，以逗号分隔
            orderCountList.add(currentOrderCount);
            // 有效订单数列表，以逗号分隔
            validOrderCountList.add(currentValidOrderCount);
            // 订单总数
            totalOrderCount += currentOrderCount;
            // 有效订单数
            validOrderCount += currentValidOrderCount;
        }

        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(localDateArrayList.stream().map(String::valueOf).collect(Collectors.joining(",")));
        orderReportVO.setOrderCountList(orderCountList.stream().map(String::valueOf).collect(Collectors.joining(",")));
        orderReportVO.setValidOrderCountList(validOrderCountList.stream().map(String::valueOf).collect(Collectors.joining(",")));
        orderReportVO.setTotalOrderCount(totalOrderCount);
        orderReportVO.setValidOrderCount(validOrderCount);
        orderReportVO.setOrderCompletionRate(validOrderCount.doubleValue() / totalOrderCount.doubleValue());

        return orderReportVO;
    }

    @Override
    public SalesTop10ReportVO SalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap<>();
        map.put("endTime", endTime);
        map.put("beginTime", beginTime);
        map.put("status", Orders.COMPLETED);

        List<GoodsSalesDTO> ordersList = reportMapper.SalesTop10(map);

        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(ordersList.stream().map(GoodsSalesDTO::getName).collect(Collectors.joining(",")));
        salesTop10ReportVO.setNumberList(ordersList.stream().map(item -> item.getNumber().toString()).collect(Collectors.joining(",")));

        return salesTop10ReportVO;
    }

    @Override
    public void export(HttpServletResponse response) throws Exception {
        // 1、查询数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        // 2、写入数据到excel
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        if (inputStream == null) {
            throw new Exception("运营数据报表模板.xlsx，为空");
        }
        XSSFWorkbook excel = new XSSFWorkbook(inputStream);
        XSSFSheet sheet1 = excel.getSheetAt(0);
        // 第2行 时间
        sheet1.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);
        // 第4行 营业额 订单完成率 新增用户数
        sheet1.getRow(3).getCell(2).setCellValue(String.valueOf(businessData.getTurnover()));
        sheet1.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate() + "%");
        sheet1.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
        // 第5行 有效订单 平均客单价
        sheet1.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
        sheet1.getRow(4).getCell(4).setCellValue(String.valueOf(businessData.getUnitPrice()));

        // 填充 30天的明细数据
        for (int i = 0; i < 30; i++) {
            LocalDate date = begin.plusDays(i);
            LocalDateTime beginDateTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endDateTime = LocalDateTime.of(date, LocalTime.MAX);
            BusinessDataVO businessDataItem = workspaceService.getBusinessData(beginDateTime, endDateTime);
            XSSFRow row = sheet1.getRow(i + 7);

            row.getCell(1).setCellValue(String.valueOf(date));
            row.getCell(2).setCellValue(String.valueOf(businessDataItem.getTurnover()));
            row.getCell(3).setCellValue(businessDataItem.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataItem.getOrderCompletionRate());
            row.getCell(5).setCellValue(String.valueOf(businessDataItem.getUnitPrice()));
            row.getCell(6).setCellValue(businessDataItem.getNewUsers());
        }


        //3、 将文件输出到前端
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);

        log.info("导出营业数据：{}到{}", begin, end);

        // 4、关闭资源（避免内存泄露）
        outputStream.close();
        excel.close();
    }


}
